package com.project.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("test")
public class TestController {
    @RequestMapping("cookie")
    public String cookie(HttpServletResponse resp){
        //添加cookie信息
        resp.addCookie(new Cookie("name","jack"));
        Cookie c = new Cookie("pwd","123");
        //设置过期时间
        c.setMaxAge(600);
        resp.addCookie(c);

        return "ok";
    }

    /**
     * 得到cookie信息
     * @param req 请求对象
     * @return
     */
    @RequestMapping("getCookie")
    public String getCookie(HttpServletRequest req){
        //得到cookie信息
        Cookie[] cookieArray = req.getCookies();
        String str = "";
        for(Cookie c : cookieArray){
            str += c.getName()+"   "+c.getValue()+"  ";
        }

        return str;
    }

    @RequestMapping("getSession")
    public String getSession(HttpServletRequest req){
        //得到session对象
        //如果有该用户对应的session对象，那么直接返回。
        //如果没有该用户对应的session对象，那么先创建session对象，然后再返回
        HttpSession session = req.getSession();
        //绑定共享数据
        session.setAttribute("name","tom");
        return session.getId();
    }
    @RequestMapping("getData")
    public String getSessionData(HttpServletRequest req){
        //得到session中绑定的共享数据
        Object obj = req.getSession().getAttribute("name");
        return obj.toString();
    }
}
